package com.yylending.las.lending.quota.idcard;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.YJKD;
import com.yylending.las.authority.login.LoginActivity;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.quota.ApplyQuotaActivity;

/**
 * Created by laixj on 2016/11/9.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class IdCardInfoFragment extends BaseFragment implements IdCardPresenter.View, View.OnClickListener {
	private final static String TAG = "IdCardInfoFragment";

	private final static String ARG_ID_CARD = "id_card";

	private final static int LOADER_ID = 209;

	//姓名
	private EditText mNameEt;
	//身份证号码
	private EditText mNumberEt;
	//签发机关
	private TextView mOfficeTv;
	//有效期
	private TextView mPeriodStartTv;
	private TextView mPeriodEndTv;
	private Button mConfirmBtn;
	private Button mRescanBtn;
	private ImageView mNameDeleteIv;

	private IdCardPresenter mIdCardPresenter;

	private IdCardModel.IdCard mIdentityCard;

	public static BaseFragment newInstance(int sectionNumber, Object param) {
		BaseFragment fragment = new IdCardInfoFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		if (null != param)
			args.putParcelable(ARG_ID_CARD, (IdCardModel.IdCard) param);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		if (null != bundle) {
			mIdentityCard = bundle.getParcelable(ARG_ID_CARD);
		}
		checkLogin();
	}

	private void checkLogin() {
		if (!YJKD.login()) {
			LoginActivity.start((RxAppCompatActivity) getActivity());
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public void onDetach() {
		dismissLoading();
		getLoaderManager().destroyLoader(LOADER_ID);
		super.onDetach();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID:
				return new PresenterLoader<>(getActivity(), new IdCardPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID:
				CLog.i(TAG, "onLoadFinished() IdCardPresenter");
				mIdCardPresenter = (IdCardPresenter) data;
				mIdCardPresenter.attach(this);
				break;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_edit_idcard_information, null);
		initView(v);
		initListener();
		initData();
		return v;
	}

	private void initData() {
		if (null != mIdentityCard) {
			mNameEt.setText(mIdentityCard.iname);
			mNumberEt.setText(mIdentityCard.inumber);
			mOfficeTv.setText(mIdentityCard.ioffice);
			mPeriodStartTv.setText(mIdentityCard.istart + "-" + mIdentityCard.iend);
			mNameEt.setSelection(mNameEt.getText().length());
		} else {
			mNameEt.setText("");
			mNumberEt.setText("");
			mOfficeTv.setText("");
			mPeriodStartTv.setText("");
		}
	}

	private void initListener() {
		mConfirmBtn.setOnClickListener(this);
		mRescanBtn.setOnClickListener(this);
		mNameDeleteIv.setOnClickListener(this);
	}

	private void initView(View view) {
		mNameEt = (EditText) view.findViewById(R.id.id_card_info_name_et);
		mNumberEt = (EditText) view.findViewById(R.id.id_card_info_number_et);
		mOfficeTv = (TextView) view.findViewById(R.id.id_card_info_office);
		mPeriodStartTv = (TextView) view.findViewById(R.id.id_card_info_period_start);
		//mPeriodEndTv = (TextView) view.findViewById(R.id.id_card_info_period_end);
		mConfirmBtn = (Button) view.findViewById(R.id.id_card_info_confirm);
		mRescanBtn = (Button) view.findViewById(R.id.id_card_info_rescan);
		mNameDeleteIv = (ImageView) view.findViewById(R.id.id_card_name_delete_iv);
		mNameEt.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().trim().length() != 0) {
					mNameDeleteIv.setVisibility(View.VISIBLE);
				} else {
					mNameDeleteIv.setVisibility(View.GONE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.id_card_info_confirm:
				CLog.i(TAG, "确定");
				//StatService.onEvent(getContext(), StatIDSet.EVENT_ID_DETERMINE_PHOTO);
				if (null == mIdentityCard) {
					showToast(R.string.scan_id_card_fail);
					return;
				}
				mIdentityCard.inumber = mNumberEt.getText().toString().toUpperCase();
				mIdentityCard.iname = mNameEt.getText().toString();
				if (TextUtils.isEmpty(mIdentityCard.iname)) {
					showToast(R.string.id_card_name_number_error);
					return;
				}
				if (TextUtils.isEmpty(mIdentityCard.inumber)) {
					showToast(R.string.id_card_name_number_error);
					return;
				}
				if (mIdentityCard.inumber.length() < 18) {
					showToast(R.string.id_card_name_number_error);
					return;
				}
				if (TextUtils.isEmpty(mIdentityCard.ioffice) || TextUtils.isEmpty(mIdentityCard.istart) || TextUtils.isEmpty(mIdentityCard.iend)) {
					showToast(R.string.scan_id_card_fail);
					return;
				}
				if (mIdentityCard.iend.contains("长期")) {
					mIdentityCard.iend = "20990101";
				}
				CLog.i(TAG, "提交身份证信息");
				YJKD.hideInputWindow(getActivity());
				showLoading(true);
				//mIdCardPresenter.saveIdCardInfo(mIdentityCard);
				break;
			case R.id.id_card_info_rescan:
				CLog.i(TAG, "重拍");
				//StatService.onEvent(getContext(), StatIDSet.EVENT_ID_TAKE_PHOTO_AGAIN);
				((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_ID_CARD_SCAN, null);
				EventAgent.post(new IdCardPresenter.Event(IdCardPresenter.Event.ID_CARD_RESCAN));
				break;
			case R.id.id_card_name_delete_iv:
				mNameEt.getText().clear();
				break;
		}
	}

	@Override
	public void saveIdCardSuccess() {
		Global.LOGIN_REAL_NAME = mIdentityCard.iname;
		((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_ID_CARD_CONFIRM, mIdentityCard);
	}

	@Override
	public void saveIdCardFail(String msg, boolean exit) {
		dismissLoading();
		if (exit) {
			showOneBtnDialog(msg, getString(R.string.got_it), mExitDialog);
		} else {
			showOneBtnDialog(msg, getString(R.string.got_it));
		}
	}

	private CommonDialog.ButtonClickListener mExitDialog = new CommonDialog.ButtonClickListener() {
		@Override
		public void onCancel(CommonDialog dialog) {
			dialog.dismiss();
		}

		@Override
		public void onConfirm(CommonDialog dialog) {
			dialog.dismiss();
			getActivity().finish();
		}
	};
}
